package com.hctforgreen.greenservice.ui.adapter;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBManager;
import com.hctforgreen.greenservice.model.BaseListItemEntity;
import com.hctforgreen.greenservice.model.PwdEntity;
import com.hctforgreen.greenservice.model.SpareBootPasswordEntity;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.irremote.GoogleIrDevice;
import com.hctforgreen.greenservice.utils.irremote.GreeIrFcode;
/**
 * 密码列表
 * 
 * @author wuhs
 * 
 */
@SuppressLint("ResourceAsColor")
public class PwdListAdapter extends BaseAdapter {
	private ArrayList<PwdEntity> pwdlist;
	private LayoutInflater mInflater;
	private Context context;
	private DBManager mgr;
	private OnClickListener click;
	public boolean isEdit = false;
	private String MachineModel;//手机型号
	private Vibrator vibrator;
	private int times = 1000*60;
	private String[] passwordList = new String[3];
	/*编码规则和发码类
     * 
     */
    public static GreeIrFcode greeFcode;
    public static GoogleIrDevice googleIrDev;
	
	private boolean isCloudServer;
	
	static class ViewHolder {
		TextView date_txt;
		TextView backuppwd_txt;
		TextView qr_code_txt;
		TextView pwd_txt;
		TextView link_backuppwd;
		ProgressBar loadPb ;
		Button button_sentPassword;
		TextView text_sentRemark;
	}
	
	
	public PwdListAdapter(Activity context, ArrayList<PwdEntity> pwdlist,
			OnClickListener click,DBManager mgr, boolean isCloudServer) {
		super();
		this.context = context;
		this.mInflater = LayoutInflater.from(context);
		this.pwdlist = pwdlist;
		this.click = click;
		this.mgr = mgr;
		this.MachineModel = android.os.Build.MODEL;
		this.isCloudServer = isCloudServer;
		Log.d("MODEL", MachineModel);
//		greeFcode=new GreeIrFcode();
//		googleIrDev=new GoogleIrDevice(context);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return pwdlist.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.item_pwd_list_view, null);
			holder.date_txt = (TextView) convertView.findViewById(R.id.date_txt);
			holder.qr_code_txt = (TextView) convertView.findViewById(R.id.qr_code_txt);
			holder.pwd_txt = (TextView) convertView.findViewById(R.id.pwd_txt);
			
			holder.backuppwd_txt = (TextView) convertView.findViewById(R.id.backuppwd_txt);
			holder.link_backuppwd = (TextView) convertView.findViewById(R.id.link_backuppwd);
			holder.loadPb =  (ProgressBar) convertView.findViewById(R.id.pb_loading);
			holder.button_sentPassword = (Button) convertView.findViewById(R.id.button_sentPassword);
			holder.text_sentRemark = (TextView) convertView.findViewById(R.id.text_sentRemark);
			
			
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		//赋值
		final PwdEntity entity = pwdlist.get(position);
		passwordList[0] = entity.openPassword;
		holder.qr_code_txt.setText("条码：" + entity.stripeCode);
		holder.pwd_txt.setText("密码：" + entity.openPassword);
		holder.date_txt.setText(entity.date);
		final ProgressBar final_loadPb = holder.loadPb;
		final TextView final_link_backuppwd = holder.link_backuppwd;
		final TextView final_backuppwd_txt = holder.backuppwd_txt;
		
		/*
		 * 大机组的无密码时，不显示获取备用密码和红外发送
		 */
		if (entity.isBigUnit.equals("1")) {
			if (entity.openPassword.equals("")) {
				holder.pwd_txt.setText("密码："
						+ context.getResources().getString(
								R.string.bigunit_password_appling));
			}
			holder.link_backuppwd.setVisibility(View.GONE);
			holder.text_sentRemark.setVisibility(View.GONE);
			holder.button_sentPassword.setVisibility(View.GONE);
			
		} else if (entity.isBigUnit.equals("0")) {
			holder.pwd_txt.setText("密码：" + entity.openPassword);
			holder.link_backuppwd.setVisibility(View.VISIBLE);
			
			/*
			 * 非格力手机，不显示获取备用密码和红外发送
			 */
			if(MachineModel.equals("G0111")||MachineModel.equals("G01111") || MachineModel.equals("G0128")
					|| MachineModel.equals("G0215D") || MachineModel.equals("G0235D")){
				holder.button_sentPassword.setVisibility(View.VISIBLE);
				holder.text_sentRemark.setVisibility(View.VISIBLE);
			}else{
				holder.button_sentPassword.setVisibility(View.GONE);
				holder.text_sentRemark.setVisibility(View.GONE);
			}
		}
		
		
		//设置发送红外密码点击事件
		holder.button_sentPassword.setOnClickListener( new OnClickListener() {
			
			public void onClick(View v) {
				//整合密码list
				int num=0;
				for (int i = 0; i < passwordList.length; i++) {
					if(passwordList[i]!=null){
						num++;
					}
				}
				final String[] ItemList = new String[num];
				int j=0;
				for (int i = 0; i < passwordList.length; i++) {
					if(passwordList[i]!=null){
						ItemList[j] = passwordList[i];
						j++;
					}
				}
				
				if(ItemList.length>1){//多于一条则弹出选择框
					new AlertDialog.Builder(context)
					.setTitle("单选框")
					.setIcon(android.R.drawable.ic_dialog_info)
					.setSingleChoiceItems(
							ItemList, 0,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									Log.d("ItemList[which]", ""+ItemList[which]);
									sendIrCode(ItemList[which]);
									dialog.dismiss();
								}
							}).setNegativeButton("取消", null).show();
				}else{
					sendIrCode(ItemList[0]);
				}
				
			}
		});
		//设置获取备用密码点击事件
		holder.link_backuppwd.setOnClickListener( new OnClickListener() {
				public void onClick(View v) {
					final_link_backuppwd.setClickable(false);
					final_loadPb.setVisibility(View.VISIBLE);
					final Handler handler = new Handler() {
						public void handleMessage(Message msg) {
							
							final_loadPb.setVisibility(View.GONE);
							final_link_backuppwd.setClickable(true);
							HctResult hctResult = new HctResult();
							switch (msg.what) {
							case HctConstants.STATUS_SUCCESS:
								hctResult = (HctResult) msg.obj;
								SpareBootPasswordEntity bean = (SpareBootPasswordEntity) hctResult.data;
								if (bean.statusCode.equals("0")) {
									String sparebootPwd = bean.bootPwd
											.replace("[", "").replace("]", "")
											.replace("\"", "");
									final_backuppwd_txt.setText("备用密码："+sparebootPwd);
									final_link_backuppwd.setText("");
									final_link_backuppwd.setClickable(false);
									
									//保存备用密码到本地
									PwdEntity updateEntity = new PwdEntity();
									updateEntity = entity;
									updateEntity.sparebootPwd = sparebootPwd;
									mgr.updateSparebootPwd(updateEntity);
									//保存备用密码到密码List，以便红外发送
									String[] backuppwdList = sparebootPwd.split("或");
									for (int i = 0; i < backuppwdList.length; i++) {
										if(i<2){//保证只存2个
											passwordList[i+1] = backuppwdList[i].trim();//要去除空格
										}
									}
								} else if (!bean.statusCode.equals("0")) {
									if (!bean.bootMsg.equals("")) {
										Toast.makeText(context, bean.bootMsg,
												Toast.LENGTH_SHORT).show();
									} else if (bean.bootMsg.equals("")) {
										Toast.makeText(context,
												context.getString(R.string.net_error_hint),
												Toast.LENGTH_SHORT).show();
									}

								}
								break;

							case HctConstants.STATUS_FAILD:
								Toast.makeText(context, context.getString(R.string.net_error_hint),
										Toast.LENGTH_SHORT).show();
								break;
							}
							
						}
					};
					new Thread() {
						public void run() {
							Message message = new Message();
							try {
								HctController controller = new HctController(context);
								HctResult result = controller.getSpareBootPwd(entity, isCloudServer);
								if (result.status == HctConstants.STATUS_SUCCESS) {
									message.what = result.status;
									message.obj = result;
								} else {
									message.what = HctConstants.STATUS_FAILD;
								}
							} catch (Exception e) {
								message.what = HctConstants.STATUS_FAILD;
								e.printStackTrace();
							}
							handler.sendMessage(message);
						}
					}.start();
					
				}
			}
		);

				
		
		return convertView;
	}

	private void sendIrCode(final String password){
		greeFcode=new GreeIrFcode();
		googleIrDev=new GoogleIrDevice(context);
		//手机震动
		vibrator = (Vibrator)context.getSystemService(Service.VIBRATOR_SERVICE);
		vibrator.vibrate(50);
				
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
					case 1:
						Toast.makeText(context,
								"已发送密码："+msg.obj.toString(),
								Toast.LENGTH_SHORT).show();
						break;
					case 2:
						Toast.makeText(context,
								"红外发送密码："+msg.obj.toString()+"异常",
								Toast.LENGTH_SHORT).show();
						break;
				}
					
			}
		};
		
		
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					//红外发射
					googleIrDev.sendIrCode(greeFcode.getRateFcodeStr(greeFcode.getPassCodeBytes(password)));
					message.what = 1;
					message.obj = password;
					handler.sendMessage(message);
				} catch (Exception e) {
					message = new Message();
					message.what = 2;
					message.obj = password;
					handler.sendMessage(message);
					e.printStackTrace();
				}finally{
					vibrator.cancel();
				}
			}
		}.start();
	}

}
